import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';

import '../../common/index.dart';

class UserInfoPage extends ConsumerStatefulWidget {
  const UserInfoPage({super.key, required this.userId});

  final String userId;

  @override
  ConsumerState<UserInfoPage> createState() => _UserInfoPageState();
}

class _UserInfoPageState extends ConsumerState<UserInfoPage> {
  UserEntity? _targetUser;
  List<ShareEntity> _userShares = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  /// 加载用户数据
  Future<void> _loadUserData() async {
    try {
      setState(() {
        _isLoading = true;
      });

      // 获取目标用户信息
      final user = await UserService.getUserById(widget.userId);
      if (user == null) {
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('user not found')));
          Navigator.of(context).pop();
        }
        return;
      }

      // 获取用户发布的分享
      final shares = await ShareService.getSharesByUserId(widget.userId);

      // 按日期降序排序
      shares.sort(
        (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
      );

      if (mounted) {
        setState(() {
          _targetUser = user;
          _userShares = shares;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('加载用户数据失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('load user data failed')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MyImages.myBg),
              fit: BoxFit.fill,
            ),
          ),
          child: const SafeArea(
            child: Center(
              child: CircularProgressIndicator(color: Color(0xFFFF8C00)),
            ),
          ),
        ),
      );
    }

    if (_targetUser == null) {
      return Scaffold(
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MyImages.myBg),
              fit: BoxFit.fill,
            ),
          ),
          child: const SafeArea(
            child: Center(
              child: Text(
                'user not found',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.myBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: _buildUserProfile(_targetUser!),
        ),
      ),
    );
  }

  /// 构建用户资料界面
  Widget _buildUserProfile(UserEntity targetUser) {
    return Stack(
      children: [
        // 返回按钮
        Positioned(
          top: 45.h,
          left: 10.w,
          child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.h,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.3),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: Colors.white,
                size: 20.sp,
              ),
            ),
          ),
        ),

        // 顶部举报按钮
        Positioned(
          top: 45.h,
          right: 10.w,
          child: InkWell(
            onTap: () {
              _showReportDialog();
            },
            child: Container(
              width: 40.w,
              height: 40.h,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.3),
                shape: BoxShape.circle,
              ),
              child: SvgPicture.asset(
                MyIcons.report,
                width: 20.w,
                height: 20.h,
                colorFilter: const ColorFilter.mode(
                  Colors.white,
                  BlendMode.srcIn,
                ),
              ),
            ),
          ),
        ),

        // 用户信息
        Positioned(
          top: 78.h,
          left: -30.w,
          child: Container(
            width: 430.w,
            height: 352.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MyImages.userInfoBg),
                fit: BoxFit.contain,
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 用户头像
                Container(
                  width: 195.w,
                  height: 195.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(MyImages.avatarBg),
                      fit: BoxFit.contain,
                    ),
                  ),
                  child: Center(
                    child: UserAvatar(
                      radius: 32.r,
                      avatarPath: targetUser.avatar,
                      fallbackAsset: MyImages.mark,
                    ),
                  ),
                ),

                // 用户名和聊天按钮
                SizedBox(
                  width: 200.w,
                  height: 32.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // VIP标志
                      if (targetUser.isVip)
                        Image.asset(MyImages.vip, width: 32.w, height: 32.h),

                      // 用户名
                      Text(
                        targetUser.username,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      SizedBox(width: 8.w),

                      // 聊天按钮
                      InkWell(
                        onTap: () {
                          _startChat(targetUser);
                        },
                        child: SvgPicture.asset(
                          MyIcons.chatIcon,
                          width: 32.w,
                          height: 32.h,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),

        // 用户的分享
        Positioned(
          top: 400.h,
          left: 0,
          right: 0,
          bottom: 0,
          child: Column(
            children: [
              // 用户发布的share
              Expanded(child: _buildUserSharesList()),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建用户分享列表
  Widget _buildUserSharesList() {
    if (_userShares.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.share_outlined,
              size: 64.sp,
              color: Colors.white.withValues(alpha: 0.5),
            ),
            SizedBox(height: 16.h),
            Text(
              'No shares yet',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.7),
                fontSize: 16.sp,
                fontFamily: 'inter',
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadUserData,
      child: ListView.builder(
        padding: EdgeInsets.only(
          left: 10.w,
          right: 10.w,
          top: 16.h,
          bottom: 65.h,
        ),
        itemCount: _userShares.length,
        itemBuilder: (context, index) {
          final share = _userShares[index];

          return GestureDetector(
            onTap: () async {
              // 增加浏览量
              await ref
                  .read(shareProvider.notifier)
                  .incrementViewCount(share.id);

              AppRouterExtension(context).navigateTo(
                AppRoutes.shareDetail,
                params: {'shareId': share.id},
              );
            },
            child: ShareItem(share: share, isSquare: false),
          );
        },
      ),
    );
  }

  /// 显示举报对话框
  void _showReportDialog() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return ReportDialog(
          targetId: widget.userId,
          reportType: ReportType.user,
          title: 'Report User',
          onReportSuccess: () {
            context.go(AppRoutes.main);
            ref.read(shareProvider.notifier).loadAllShares();
            final currentUser = UserService.getCurrentUser();
            if (currentUser != null) {
              ref
                  .read(messageProvider.notifier)
                  .loadConversations(currentUser.id);
            }
          },
        );
      },
    );
  }

  /// 开始聊天
  void _startChat(UserEntity targetUser) {
    if (ref.read(currentUserProvider) == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please login first'),
          backgroundColor: Color(0xFFFF8C00),
        ),
      );
      return;
    }

    if (targetUser.id == ref.read(currentUserProvider)?.id) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('You cannot chat with yourself'),
          backgroundColor: Color(0xFFFF8C00),
        ),
      );
    } else {
      context.navigateTo('${AppRoutes.chat}/${targetUser.id}');
    }
  }
}
